﻿using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using Core.Caching;
using Core.Domain.Entities;
using Core.Helpers;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Identity.Roles.Caching;
using Core.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.Roles.Features.Commands.Create;

/// <summary>
/// 创建角色
/// </summary>
public class CreateRoleCommand : ICacheInvalidatorRequest<Result<Guid>>
{
    /// <summary>
    /// 编码
    /// </summary>
    [Required(ErrorMessage = "编码必传")]
    public required string Code { get; set; }
    /// <summary>
    /// 角色名
    /// </summary>
    [Required(ErrorMessage = "角色名必传")]
    public required string Name { get; set; }
    /// <summary>
    /// 设置排序
    /// </summary>
    public int? Sort { get; set; }
    /// <summary>
    /// 设置描述
    /// </summary>
    public string? Description { get; set; }
    /// <summary>
    /// 设置启用/禁用
    /// </summary>
    public bool Enabled { get; set; }

    [JsonIgnore]
    public IEnumerable<string>? Tags => RolesCacheKey.Tags;
}

public class CreateRoleCommandHandler(IIdentityDbContext dbContext) : IRequestHandler<CreateRoleCommand, Result<Guid>>
{

    public async Task<Result<Guid>> Handle(CreateRoleCommand request, CancellationToken cancellationToken)
    {
        var role = await dbContext.Roles
            .FirstOrDefaultAsync(x => x.Name == request.Name, cancellationToken);
        ExceptionHelper.ThrowIfNotNull(role, "角色名已存在");

        role = await dbContext.Roles
            .FirstOrDefaultAsync(x => x.Code == request.Code, cancellationToken);
        ExceptionHelper.ThrowIfNotNull(role, "编号已被占用");

        role = Role.Create(request.Code, request.Name, request.Description, request.Sort, request.Enabled);

        await dbContext.Roles.AddAsync(role);

        var result = await dbContext.SaveChangesAsync(cancellationToken) > 0;
        return await Result<Guid>.SucceedAsync(result, role.Id, ["创建失败"]);
    }
}
